﻿<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <title>2.8节,限制字符串的长度</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<h2>限制字符串的长度</h2>
通过“maxlength ”限制：<input type="text" name="lname" maxlength="5" /><br />
通过“JavaScript事件 ”限制：<input type="text" data-length='5' id='limitLength' data-model='Ch' name="lname"/><br />

<script type="text/javascript">
    window.onload = function(){
        var limitLength = document.getElementById("limitLength"),		//获取限制对象
                clearNonumber = function(tThis){					//清除数字
                    var _v = tThis.value,
                            _vLen = _v.length,
                            dataLength = tThis.getAttribute("data-length"),//获取长度属性
                            dataModel = tThis.getAttribute("data-model"),
                            subLen = dataLength;
                    if(_vLen > dataLength)  tThis.value = _v.substr(0, subLen);//判断长度
                };
        limitLength.onfocus = function(){							//获取焦点事件
            clearNonumber(this);
        }
        limitLength.onkeyup = function(){							//键盘事件
            clearNonumber(this);
        }
        limitLength.onblur = function(){							//失去焦点事件
            clearNonumber(this);
        }
    };
</script>

</body>
</html>
